#!/usr/bin/env python
# Create: 2019/5/6
__author__ = '749B'
"""分析event信息
获取节点通断的时间，以及节点的信息
时间需要加8小时变成北京时间
"""

import requests
from orionsdk import SwisClient

from sds import settings

npm_server = settings.npm_server
username = settings.username
password = settings.password


def get_info_by_ip(ip_addr):
    swis = SwisClient(npm_server, username, password)
    results = swis.query("SELECT Uri FROM Orion.Nodes WHERE IP=@ip_addr",ip_addr=ip_addr)
    if len(results['results']) == 0:
        print("未查询到任何节点")
        return
    elif len(results['results']) > 1:
        print("查询到多个节点:", results['results'])
    uri = results['results'][0]['Uri']
    obj = swis.read(uri + '/')
    obj2 = swis.read(uri + '/CustomProperties')
    return obj['Caption'], str(obj['NodeID']), str(obj['EngineID']), str(obj2['Department']), str(obj2['City'])


def get_events(oid):
    swis = SwisClient(npm_server, username, password)
    results = swis.query("SELECT Uri FROM Orion.Events "
                         "WHERE NetObjectType='N' AND EventType IN (1, 5) AND "
                         "EventTime > GETDATE()-7.55 AND EventTime < GETDATE()-5.9 AND "
                         "NetObjectID=@oid", oid=oid)
    for result in results['results']:
        uri = result['Uri']
        obj = swis.read(uri)
        # print("%s\t%s\t%s" % (obj['EventTime'], obj['EventType'], obj['Message']))
        yield obj['EventTime'], str(obj['EventType'])


requests.packages.urllib3.disable_warnings()


def pd_main():
    import sys
    sys.path.append(r'D:\Python36\Lib\site-packages')
    import pandas as pd
    file = r'C:\Users\Steed\Desktop\out2.csv'
    df = pd.read_csv(file, header=None, names=['time', 'title', 'lv', 'message', 'ip', 'dept', 'city', 'node'])
    df = df[df.dept != "IDX金桥DC"]
    df.dept.fillna("N/A", inplace=True)
    df.city.fillna("N/A", inplace=True)
    df = df.drop_duplicates(["ip"], keep="last")
    print("总共: %d" % len(df))
    for _, row in df.iterrows():
        yield row.ip


if __name__ == '__main__':
    import time
    file = open('alarts_timeline.csv', 'a', encoding='utf-8')
    n = 0
    start = time.time()
    for ip_addr in pd_main():
        n += 1
        if n < 273:
            continue
        node, oid, engine, dept, city = get_info_by_ip(ip_addr)
        print("\r已处理: %d\t用时: %.2f秒\t正在处理: %s - %s" % (n, time.time()-start, ip_addr, node), end='')
        for event_time, event_type in get_events(oid):
            file.write("%s\n" % ','.join([event_time, event_type, node, ip_addr, oid, engine, dept, city]))

    file.close()






